package com.feige.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.feige.constant.Constants;
import com.feige.service.UploadService;
import com.feige.utils.aliyun.AliyunOssHandler;
import com.feige.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author feige<br />
 * @ClassName: UploadServiceImpl <br/>
 * @Description: <br/>
 * @date: 2021/3/1 15:55<br/>
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {
    @Override
    public AjaxResult upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        log.info("=====上传文件====" + originalFilename);
        if (originalFilename != null && originalFilename.equals(Constants.BLOB)){
            originalFilename = "feige.jpg";
        }
        int lastIndexOf;
        boolean upload = false;
        String fileAddr = AliyunOssHandler.BUCKET_URL;
        String name = "";
        if (originalFilename != null &&
                (lastIndexOf = originalFilename.lastIndexOf(".")) != -1
        ){
            String fileType = originalFilename.substring(lastIndexOf + 1);
            String fileName = IdUtil.simpleUUID() + "." + fileType;
            if (Arrays.asList(Constants.IMG_TYPE).contains(fileType)){
                name = AliyunOssHandler.joinFileName("image", fileName);
            }else if (Arrays.asList(Constants.VOICE_TYPE).contains(fileType)){
                name = AliyunOssHandler.joinFileName("voice",fileName);
            }else if (Arrays.asList(Constants.FILE_TYPE).contains(fileType)){
                name = AliyunOssHandler.joinFileName("file",fileName);
            }
            if (StrUtil.isNotBlank(name)){
                upload = AliyunOssHandler.upload(name,inputStream);
            }
        }
        fileAddr += name;
        log.info("=====文件地址====" + fileAddr);
        return upload? AjaxResult.success(fileAddr):AjaxResult.error();
    }

    @Override
    public AjaxResult uploadBase64Data(String base64Data) {
        log.info("==上传base64图片==");
        //base64格式前头
        String dataPrefix = "";
        //实体部分数据
        String data = "";
        if(StrUtil.isNotBlank(base64Data)) {
            //将字符串分成数组
            String[] d = base64Data.split("base64,");
            if (d.length == 2){
                dataPrefix = d[0];
                data = d[1];
            }
        }else {
            return AjaxResult.error();
        }
        //图片后缀，用以识别哪种格式数据
        String suffix = "";
        //编码的jpeg图片数据
        if(Constants.BASE64_TYPE[0].equalsIgnoreCase(dataPrefix)){
            suffix = ".jpg";
        }else if(Constants.BASE64_TYPE[1].equalsIgnoreCase(dataPrefix)){
            //编码的icon图片数据
            suffix = ".ico";
        }else if(Constants.BASE64_TYPE[2].equalsIgnoreCase(dataPrefix)){
            //编码的gif图片数据
            suffix = ".gif";
        }else if(Constants.BASE64_TYPE[3].equalsIgnoreCase(dataPrefix)){
            //编码的png图片数据
            suffix = ".png";
        }else {
            return AjaxResult.error();
        }
        log.info("=====图片格式====" + suffix);
        String uuid = IdUtil.simpleUUID();
        String fileName = uuid + suffix;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {
                    //调整异常数据
                    b[i]+=256;
                }
            }
            String name = AliyunOssHandler.joinFileName("image", fileName);
            String fileAddr = AliyunOssHandler.BUCKET_URL + name;
            boolean upload = AliyunOssHandler.upload(name, new ByteArrayInputStream(b));
            log.info("==上传结束==");
            return upload? AjaxResult.success(fileAddr):AjaxResult.error();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("==出错==");
            return AjaxResult.error();
        }
    }
}
